<template>
  <div>
    <div class="infoBlock">
      <div class="info">
        <div class="avatar">
          <uploader class="uploader" :after-read="onRead">
            <img :src="photo" alt="">
          </uploader>
            <div  class="national" v-show="conronPic">
              <div  class="van-image" style="width: 20px;" >
                <img :src=conronPic class="van-image__img" />
              </div>
            </div>
        </div>
        <div class="text">
          <p class="name">
            <span>{{name}}</span>
            <img src="@as/img/dangyuan.png" alt="">
            <span>{{party_posts}}</span>
          </p>
          <p class="com">{{organization}}</p>
          <p class="date">{{party_time|time}} 入党</p>
        </div>
      </div>
      <ul class="nav">
        <li @click="goSubscription">
          <img src="@as/img/wode_wddy@2x.png" alt>
          <span>我的订阅</span>
        </li>
        <li @click="goCollection">
          <img src="@as/img/wode_wdsc@2x.png" alt>
          <span>我的收藏</span>
        </li>
        <li @click="goMyNotes">
          <img src="@as/img/wode_wdbj@2x.png" alt>
          <span>我的笔记</span>
        </li>
        <li @click="goReport">
          <img src="@as/img/wode_sxhb@2x.png" alt>
          <span>思想汇报</span>
        </li>
      </ul>
    </div>
    <ul class="MyNavList">
      <li @click="goUserInfo">
        <img src="@as/img/wode_grxx@2x.png" alt="">
        <span>个人信息</span>
        <img src="@as/img/wode_arrow.png" alt="">
      </li>
      <li @click="goOrganization">
        <img src="@as/img/wode_zbxx@2x.png" alt="">
        <span>支部信息</span>
        <img src="@as/img/wode_arrow.png" alt="">
      </li>
      <li @click="goAssessment">
        <img src="@as/img/wode_khxx@2x.png" alt="">
        <span>考核信息</span>
        <img src="@as/img/wode_arrow.png" alt="">
      </li>
      <li @click="goPartyPayment">
        <img src="@as/img/wode_dfjn@2x.png" alt="">
        <span>党费缴纳</span>
        <img src="@as/img/wode_arrow.png" alt="">
      </li>
      <li @click="goSetting">
        <img src="@as/img/wode_xtsz@2x.png" alt="">
        <span>系统设置</span>
        <img src="@as/img/wode_arrow.png" alt="">
      </li>
    </ul>
    <div class="nation-page" v-if="hideNation">
      <div class="nation-option">
        <p class="nation-title">配置小角标</p>
        <ul>
          <li class="active" v-for="(item,index) in photoArr" @click.stop="clickThis(index)" :key="index">
            <img :src=item alt="">
            <i
                    :class="index ==activeIndex?'iconxuexi_pinglun_gongbu red':'lay'"
                    class="iconfont "
            ></i>
          </li>
        </ul>
        <p class="mine-submit">
          <mu-button color="primary" small @click.stop="submitConfirm">确定</mu-button>
          <mu-button color="error" small  @click.stop="cancelSubmit">取消</mu-button>
        </p>
      </div>
    </div>

  </div>
</template>

<script>
import uploader from 'vant/lib/uploader';
import 'vant/lib/uploader/style';
import axios from 'axios';
import html2canvas from 'html2canvas';
import pic1 from '@as/img/3615e284800545190c9c8153e79995ec.png'
import pic2 from '@as/img/fe3349a5200c172c25416d8a6887fc9b.png'
import pic3 from '@as/img/national.7c84175e.png'
export default {
  data() {
    return {
      name: '',
      photo: '',
      file:{},
      party_posts: '',
      organization: '',
      party_time: '',
      activeIndex:-1,
      conronPic:'',
        hideNation:false,
        photoArr:[
            pic1,
            pic2,
            pic3
        ],
      qiniuData: {
        token: '',
        key: ''
      },
    };
  },
  created(){
    let data = JSON.parse(Cookies.get('user_71ydj'))
    this.name = data.name
    this.photo = data.photo
    this.party_posts = data.party_posts
    this.organization = data.organization
    this.party_time = data.party_time
    this.getToken()
  },
  mounted() {
    this.$progress.done()
  },
  methods: {
      cancelSubmit(){
          this.conronPic ='';
          this.hideNation =false;
          this.qiniuData.key = this.guid();
          this.qiniuData.file = this.file.file;
          let param = new FormData(); //创建form对象
          param.append('chunk','0');//断点传输
          param.append('chunks','1');
          param.append('file',this.file.file,this.file.file.name)
          param.append('token',this.qiniuData.token)
          param.append('key',this.qiniuData.key)
          console.log(param.get('file')); //FormData私有类对象，访问不到，可以通过get判断值是否传
          const url = `https://up-z2.qiniup.com`
          let that = this
          axios.post(url,param,{headers: {'Content-Type':'multipart/form-data'}}).then(res=>{
              let pic = `https://media.71ydj.com/${res.data.key}`
              that.$http.post(`app/login/editphoto`,{
                  uid: JSON.parse(Cookies.get('user_71ydj')).id,
                  photo: pic
              }).then(res=>{
                  that.photo = pic;
                  let data = JSON.parse(Cookies.get('user_71ydj'))
                  data.photo = pic
                  Cookies.set('user_71ydj', data, { expires: 7 })
              })
          })
      },
      //正常上传图片

      submitConfirm(){
          let  that =this;
          if(this.activeIndex>=0){
              this.conronPic =this.photoArr[this.activeIndex];
              this.$nextTick(()=>{
                  setTimeout(()=>{
                      html2canvas(document.querySelector('.avatar'), {async: false}).then(function (canvas) {
                          return new Promise((resolve, reject) => {
                              that.src = canvas.toDataURL("image/png");
                              console.log(that.src)
                              resolve(that.putb64(that.src))
                          })
                      })
                  },2000)
              })
          }else{
              this.conronPic='';
              that.cancelSubmit()
          }
            this.hideNation =false;
      },
      clickThis(i){
        this.activeIndex =i;
    },
    goUserInfo() {
      this.$router.push('/mine/UserInfo')
    },
    goMyNotes() {
      this.$router.push('/mine/MyNotes')
    },
    goAssessment(){
      this.$router.push('/home/bigData/assessment')
    },
    goPartyPayment() {
      this.$router.push('/mine/PartyPayment')
    },
    goSubscription(){
      this.$router.push('/learn/subscription')
    },
    goCollection() {
      this.$router.push('/mine/Collection')
    },
    goReport() {
      this.$router.push('/mine/report')
    },
    goOrganization(){
      this.$router.push('/mine/Organization')
    },
    goSetting(){
      this.$router.push('/mine/Setting')
    },
    S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    },
    guid() {
      return (this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4());
    },
      /*picBase是base64图片带头部的完整编码*/
      putb64(picBase) {
          let that = this;
          /*picUrl用来存储返回来的url*/
          var picUrl;
          /*把头部的data:image/png;base64,去掉。（注意：base64后面的逗号也去掉）*/
          picBase = picBase.substring(22);

          /*通过base64编码字符流计算文件流大小函数*/
          function fileSize(str) {
              var fileSize;
              if (str.indexOf('=') > 0) {
                  var indexOf = str.indexOf('=');
                  str = str.substring(0, indexOf);//把末尾的’=‘号去掉
              }

              fileSize = parseInt(str.length - (str.length / 8) * 2);
              return fileSize;
          }

          /*把字符串转换成json*/
          function strToJson(str) {
              var json = eval('(' + str + ')');
              return json;
          }


          var url = "https://upload-z2.qiniup.com/putb64/" + fileSize(picBase);
          var xhr = new XMLHttpRequest();

          xhr.onreadystatechange = function () {
              if (xhr.readyState == 4) {
                  var keyText = xhr.responseText;

                  /*返回的key是字符串，需要装换成json*/
                  keyText = strToJson(keyText);

                  /* http://ojvh6i96g.bkt.clouddn.com/是我的七牛云空间网址，keyText.key 是返回的图片文件名*/
                  picUrl = "https://media.71ydj.com/" + keyText.key;
                  that.photo = picUrl;
                  that.$http.post(`app/login/editphoto`, {
                      uid: JSON.parse(Cookies.get('user_71ydj')).id,
                      photo: picUrl
                  }).then(res => {
                      that.photo = picUrl;
                      let data = JSON.parse(Cookies.get('user_71ydj'));

                      // that.$alert('上传图片成功，是否需要配置角标','提示',)
                      data.photo = picUrl;
                      Cookies.set('user_71ydj', data, {expires: 7})
                  })
              }
          }
          xhr.open("POST", url, true);
          xhr.setRequestHeader("Content-Type", "application/octet-stream");
          xhr.setRequestHeader("Authorization", 'UpToken ' + this.qiniuData.token);
          xhr.send(picBase);
      },

    onRead(file) {
         //添加国旗图标
        let that = this;
        this.conronPic = '';
        that.photo = file.content;
        console.log(file)
        this.file =file;
        this.qiniuData.key = this.guid()
        this.qiniuData.file = file.file;
        console.log(this.qiniuData.token)
        let param = new FormData(); //创建form对象
        param.append('chunk','0');//断点传输
        param.append('chunks','1');
        param.append('file',file.file,file.file.name)
        param.append('token',this.qiniuData.token)
        param.append('key',this.qiniuData.key)
        console.log(param.get('file')); //FormData私有类对象，访问不到，可以通过get判断值是否传
        const url = `https://up-z2.qiniup.com`;
        that.$confirm('是否需要配置图片角标？', '提示', {

        }).then(({ result }) => {
            if (result) {
                that.hideNation =true;
                  // setTimeout(()=>{
                  //     html2canvas(document.querySelector('.avatar'), {async: false}).then(function (canvas) {
                  //         return new Promise((resolve, reject) => {
                  //             that.src = canvas.toDataURL("image/png");
                  //             that.putb64(that.src)
                  //         })
                  //     })
                  // },2000)
            } else {
                that.hideNation =false;
                that.conronPic =''
                that.cancelSubmit();
            }
        });
    },
    getToken() {
      const url = `index/index/qiniu`
      this.$http.post(url).then(res => {
        this.qiniuData.token = res.data.token
      })
    },
  },
  components: {
    uploader
  }
};
</script>

<style scoped lang="scss">
.infoBlock{
  position: relative;
  width: 100%;
  height: 232px;
  background: url(../../assets/img/wode_bg.png) center no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  padding: 70px 16px;
  margin-bottom: 56px;
  .info{
    display: flex;
    .avatar{
      width:61px;
      height:61px;
      background:transparent;
      border-radius: 6px;
      /*border-radius:50%;*/
      overflow: hidden;
      margin-right: 15px;
      margin-top: 3px;
      position: relative;
      .uploader{
        width: 100%;
        height: 100%;
        img{
          width: 100%;
          height: 100%;
        }
      }
      .national{
        position: absolute;
        right: 0;
        bottom: 0;
        line-height: 1;
        height: 25px;
      }
      .van-image {
        position: relative;
        display: inline-block;
      }
      .van-image__error, .van-image__img, .van-image__loading {
        display: block;
        width: 100%;
        height: 100%;
      }
    }
    .text{
      flex: 1;
      .name{
        display: flex;
        align-items: baseline;
        margin-bottom: 12px;
        span{
          &:first-of-type{
            font-size:17px;
            line-height: 17px;
            font-family:PingFang-SC-Medium;
            font-weight:500;
            color:rgba(255,255,255,1);
          }
          &:last-of-type{
            font-size:12px;
            line-height: 12px;
            font-family:PingFang-SC-Medium;
            font-weight:500;
            color:rgba(255,255,255,1);
          }
        }
        img{
          width:10px;
          height:12px;
          margin-left: 9px;
          margin-right: 5px;
        }
      }
      .com{
        font-size:12px;
        line-height: 12px;
        font-family:PingFang-SC-Medium;
        font-weight:500;
        color:rgba(255,255,255,1);
        margin-bottom: 15px;
      }
      .date{
        font-size:12px;
        line-height: 12px;
        font-family:PingFang-SC-Medium;
        font-weight:500;
        color:rgba(255,255,255,.6);
      }
    }
  }
  .nav{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: -34px;
    width:330px;
    height:100px;
    background:rgba(255,255,255,1);
    box-shadow:3px 3px 10px 0px rgba(51,51,51,0.08);
    border-radius:6px;
    display: flex;
    justify-content: center;
    li{
      height: 100%;
      display: flex;
      flex-direction: column;
      list-style: none;
      align-items: center;
      justify-content: center;
      font-size:12px;
      font-family:PingFang-SC-Medium;
      font-weight:500;
      color:rgba(51,51,51,1);
      line-height:10px;
      margin-right: 27px;
      &:last-of-type{
        margin: 0;
      }
      img{
        width: 46px;
        height: 46px;
        margin-bottom: 5px;
      }
    }
  }
}
.MyNavList{
  box-sizing: border-box;
  padding: 0 23px;
  padding-bottom: 70px;
  li{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 52px;
    font-size:14px;
    font-family:PingFang-SC-Medium;
    font-weight:500;
    color:rgba(51,51,51,1);
    img{
      &:first-of-type{
        width:15px;
        height:15px;
        margin-right: 8px;
      }
      &:last-of-type{
        width:6px;
        height:10px;
      }
    }
    span{
      flex:1;
    }
  }
}
.nation-page{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.4);
  z-index: 9999;

  .nation-option{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 350px;
    height: 400px;
    background: white;
    border-radius: 5px;
    .nation-title{
      text-align: center;
      font-size: 14px;
      color: #333;
      margin: 10px 0;
    }
    ul{
     height: 300px;
      overflow-y: scroll;
      li{
        width: 33%;
        display: inline-block;
        height: 80px;
        text-align: center;
        position: relative;
        &.active{
          i{
            position: absolute;
            right: 0;
            top:0 ;
            content: '';
            width: 20px;
            height: 20px;
            /*border-radius: 50%;*/
            /*background: rgba(0,0,0,0.4);*/
          }
        }

        img{
          width: 80px;
          height: 80px;
          border-radius: 50%;
        }
      }
    }
  }
}
.red {
  color: #eb4d44;
  font-size: 18px;
}
.lay {
  font-size: 18px;
}
  .mine-submit{
    text-align: center;
    button{
      margin: 0 20px;
    }
  }
</style>